<template>
  <div class="">
    <div class="filter-container">
      <el-button v-permission="['role:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="toSave">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中..." border fit highlight-current-row>
      <el-table-column align="center" label="角色名称" prop="name" />
      <el-table-column align="center" label="说明" prop="remark" />
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['role:detail']" type="primary" size="mini" @click="toEdit(scope.row)">编辑</el-button>
          <el-button v-permission="['role:delete']" type="danger" size="mini" @click="remove(scope.row)">删除</el-button>
          <el-button v-permission="['role:auth']" type="primary" size="mini" @click="toPermission(scope.row)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :close-on-click-modal="false" :title="isAdd?'新增角色':'编辑角色'" :visible.sync="roleFormVisible" @close="closeFormDialog">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="dataForm.name" maxlength="20"/>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="dataForm.remark" maxlength="200"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFormDialog">取消</el-button>
        <el-button v-permission="['role:add']" v-if="isAdd" type="primary" @click="save">确定</el-button>
        <el-button v-permission="['role:edit']" v-else type="primary" @click="edit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="menuFormVisible" title="权限配置" width="400px" @open="openMenuDialog" @close="closeMenuDialog">
      <el-alert :closable="false" title="角色权限发生改变后用户需重新登录方可生效" type="warning"/>
      <el-tree ref="tree" :data="menus" :default-checked-keys="assignedMenus" show-checkbox node-key="id" highlight-current default-expand-all>
        <span slot-scope="{ node, data }">
          <span>{{ data.name }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuFormVisible = false">取消</el-button>
        <el-button v-permission="['role:auth']" type="primary" @click="savePermission">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { RoleService, MenuService } from '@/api/AdminService'
import Notify from '@/utils/notify'

export default {
  name: 'Role',
  data() {
    return {
      list: null, isAdd: true, listLoading: true,
      dataForm: { id: undefined, name: undefined, remark: undefined }, roleFormVisible: false,
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      menuFormVisible: false, menus: [], assignedMenus: [],
      menuForm: { roleId: undefined, menus: [] }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    initList() {
      this.listLoading = true
      RoleService.listRole().then(result => {
        this.list = result
        this.listLoading = false
      })
    },
    closeFormDialog() {
      this.roleFormVisible = false
      this.dataForm.id = undefined
      this.dataForm.name = undefined
      this.dataForm.remark = undefined
    },
    toSave() {
      this.isAdd = true
      this.roleFormVisible = true
    },
    save() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          RoleService.addRole(this.dataForm).then(response => {
            this.roleFormVisible = false
            Notify.success(this, '新增角色成功!')
            this.initList()
          })
        }
      })
    },
    toEdit(row) {
      this.isAdd = false
      this.dataForm = Object.assign({}, row)
      this.dataForm.id = row.id
      this.roleFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    edit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          RoleService.editRole(this.dataForm).then(() => {
            this.roleFormVisible = false
            Notify.success(this, '更新角色成功!')
            this.initList()
          })
        }
      })
    },
    remove(row) {
      this.$confirm('删除角色将会回收已授权的用户权限,您确定要删除 ' + row.name + ' 的角色吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        RoleService.deleteRole(row.id).then(() => {
          Notify.success(this, '删除角色成功!')
          this.initList()
        })
      })
    },
    openMenuDialog() {
      MenuService.listMenuNames().then(result => {
        const array = []
        array.push({ id: 0, name: '根菜单', children: result })
        this.menus = array
      })
    },
    closeMenuDialog() {
      this.menuFormVisible = false
      this.menuForm.roleId = undefined
      this.menuForm.menus = []
    },
    toPermission(row) {
      this.menuFormVisible = true
      this.menuForm.roleId = row.id
      RoleService.getMenuByRole(row.id).then(result => {
        this.assignedMenus = []
        if (result) {
          result.forEach(item => {
            this.assignedMenus.push(item.id)
          })
        }
      })
    },
    savePermission() {
      this.menuForm.menus = this.$refs.tree.getCheckedKeys(true)
      RoleService.bindRoleAndMenu(this.menuForm.roleId, this.menuForm.menus).then(() => {
        this.closeMenuDialog()
        Notify.success(this, '授权成功!')
      })
    }
  }
}
</script>
